package net.keebook.webapp.bean;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import net.keebook.webapp.dao.UserDao;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.BCrypt;
import net.keebook.webapp.util.MessageBundle;
import net.keebook.webapp.util.Messages;

@ManagedBean
@RequestScoped
public class ChangePasswordBean {
	private String currentPassword;
	private String password;
	private Boolean passwordChecked;
	private SessionModel sessionModel;
	
	@Inject
	private UserDao userDao;
	
	@PostConstruct
	public void init() {
		setSessionModel(SessionModel.getInstance(FacesContext.getCurrentInstance()));
	}
	
	public void apply() throws IOException {
		User user = getUserDao().get(getSessionModel().getUserId());
		user.setHashedPassword(BCrypt.hashpw(getPassword(), BCrypt.gensalt()));
		getUserDao().update(user);
		FacesContext.getCurrentInstance().getExternalContext().redirect("changepassword.xhtml?msg="+Messages.PASSWORD_CHANGED);
	}
	
	public void validateCurrentPassword(FacesContext context, UIComponent toValidate, Object value) {
		User user = getUserDao().get(getSessionModel().getUserId());
		if (!BCrypt.checkpw((String)value, user.getHashedPassword())) {
			((UIInput)toValidate).setValid(false);
			context.addMessage(toValidate.getClientId(context), new FacesMessage(MessageBundle.get().getString("error.wrongPassword")));
		}
	}
	
	public String getCurrentPassword() {
		return currentPassword;
	}
	public void setCurrentPassword(String currentPassword) {
		this.currentPassword = currentPassword;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public SessionModel getSessionModel() {
		return sessionModel;
	}

	public void setSessionModel(SessionModel sessionModel) {
		this.sessionModel = sessionModel;
	}

	public Boolean getPasswordChecked() {
		return passwordChecked;
	}

	public void setPasswordChecked(Boolean passwordChecked) {
		this.passwordChecked = passwordChecked;
	}
}
